/**
 * ListFilterCumulate.java
 *
 * Copyright (c) 2010 Teamnet International All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of Teamnet International .
 **/
package ro.prjmanager.core.list;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"unchecked"})
public class ListFilterCumulate {
    private static final Log log = LogFactoryImpl.getLog(ListFilterCumulate.class);

    public String manageFilters(boolean cumulate, String idListener, String idRListener,
                                String propertyName, String propertyValue,
                                HttpServletRequest servletRequest) {
        String mess = null;
        if (idListener != null && idRListener != null && idListener.equals(idRListener)) {
            Object dirtyOpp = servletRequest.getSession().getAttribute(ListSessionAttributes.DIRTY_ENTITY_KEY.name());
            if (cumulate) {
                servletRequest.getSession().removeAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey());
                Map<String, FilterPair> objs = new HashMap<String, FilterPair>();
                objs.put(idListener, new FilterPair(propertyName, propertyValue));
                servletRequest.getSession().setAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey(), objs);
            }
            if (dirtyOpp != null)
                return "Exista operatii pe sesiune nesalvate!<br>Pentru a ramane in selectia actuala,<br>apasati Save.<br>Pentru a merge la selectia dorita,<br>apasati Forward!!";
        }
        if (cumulate) {
            Object cumul = servletRequest.getSession().getAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey());
            if (cumul != null) {
                Map<String, FilterPair> objs = (Map<String, FilterPair>)
                        servletRequest.getSession().getAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey());
                if (objs.containsKey(idListener)) {
                    objs.put(idListener, new FilterPair(propertyName, propertyValue));
                    servletRequest.getSession().setAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey(), objs);
                }


            } else {
                Map<String, FilterPair> objs = new HashMap<String, FilterPair>();
                objs.put(idListener, new FilterPair(propertyName, propertyValue));
                servletRequest.getSession().setAttribute(ListSessionAttributes.CUMULATE_FILTERS_KEY.getSessionKey(), objs);
            }

        }
        return mess;

    }
}
